package model

import "gorm.io/gorm"

type PassageLike struct {
	PassageID int            `gorm:"not null"`
	UserID    int            `gorm:"not null"`
	DeletedAt gorm.DeletedAt `gorm:"index"`
	Passage   *Passage       `gorm:"foreignKey:PassageID"`
	User      *User          `gorm:"foreignKey:UserID"`
}

func (p *PassageLike) SavePassageLike() (*PassageLike, error) {
	err := DB.Create(&p).Error
	if err != nil {
		return &PassageLike{}, err
	}
	return p, nil
}

func (p *PassageLike) DeletePassageLike() (*PassageLike, error) {
	err := DB.Where("PassageID = ? AND UserID = ?", p.PassageID, p.UserID).Delete(&p).Error
	if err != nil {
		return &PassageLike{}, err
	}
	return p, nil
}

func IfLiked(pid int, uid int) (bool, error) {
	var count int64
	err := DB.Model(&PassageLike{}).Where("PassageID = ? AND UserID = ?", pid, uid).Count(&count).Error
	if err != nil {
		return false, err
	} else if count == 0 {
		return false, nil
	}
	return true, nil
}
